package com.sheng.project.study.springaop.demo1;

import org.junit.Test;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.aop.framework.ProxyFactory;

import java.lang.reflect.Method;

/**
 * @author liusheng
 * @date 2023/07/05
 */
public class AopTest4 {

    @Test
    public void test1() {
        // 测试权限通知
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(new FundsService());
        proxyFactory.addAdvice(new MethodBeforeAdvice() {
            @Override
            public void before(Method method, Object[] args, Object target) throws Throwable {
                String name = (String) args[0];
                if (!"黄金鹏".equals(name)) {
                    throw new RuntimeException(String.format("[%s]禁止访问", name));
                }
            }
        });
        FundsService proxy = (FundsService) proxyFactory.getProxy();
        proxy.recharge("黄金鹏", 100);
        proxy.recharge("柳圣", 100);
    }

    @Test
    public void test2() {
        // 测试异常通知
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(new FundsService());
        proxyFactory.addAdvice(new SendMsgThrowsAdvice());
        FundsService proxy = (FundsService) proxyFactory.getProxy();
        proxy.cashOut("黄金鹏", 1000);
        proxy.cashOut("柳圣", 2000);
    }

    public static class SendMsgThrowsAdvice implements ThrowsAdvice {
        //注意方法名称必须为afterThrowing
        public void afterThrowing(Method method, Object[] args, Object target, RuntimeException ex) {
            //监控到异常后发送消息通知开发者
            System.out.println("***");
            System.out.println("IllegalArgumentException Capture");
            System.out.println("Caught: " + ex.getClass().getName());
            System.out.println("Method: " + method.getName());
            System.out.println("***\n");
        }
    }
}
